import React, { FC, useState } from 'react'
import { Wrap } from './style'
import avatar_24x24 from '@/assets/avatar/avatar_24x24.png'
import avatar_32x32 from '@/assets/avatar/avatar_32x32.png'
import avatar_64x64 from '@/assets/avatar/avatar_64x64.png'
import avatar_128x128 from '@/assets/avatar/avatar_128x128.png'
import meeting_room_24x24 from '@/assets/avatar/meeting_room_24x24.png'
import meeting_room_32x32 from '@/assets/avatar/meeting_room_32x32.png'
import meeting_room_64x64 from '@/assets/avatar/meeting_room_64x64.png'
import meeting_room_128x128 from '@/assets/avatar/meeting_room_128x128.png'
import { useGlobalStore } from '@/store/global'
export type Ix =
	| {
			name: string
			portrait: string
			accountType: 1 | 4 | 5 | 6 | 7 | 8 | 2
			isMt: true
			isPhone: boolean
			isSimpleCascade: boolean
			status: {
				isOnline: boolean
				isManager: boolean
			}
	  }
	| {
			isMt: false
			name: string
			status: {
				isOnline: boolean
				isManager: boolean
			}
	  }
interface KImagProps {
	src: string
	size?: number
	accountType: 1 | 4 | 5 | 6 | 7 | 8 | 2
}
interface AvatarProps<T extends Ix> {
	value: T
}
//获取默认头像地址
// TODO： 原代码只判断了 2：会议室 的情况，实际还有电话终端，会议等情况。
function getDefaultAvatarUrl(accountType: 1 | 4 | 5 | 6 | 7 | 8 | 2, size: number): string {
	if (accountType === 2) {
		switch (size) {
			case 24:
				return meeting_room_24x24
			case 32:
				return meeting_room_32x32
			case 64:
				return meeting_room_64x64
			case 128:
				return meeting_room_128x128
			default:
				return meeting_room_32x32
		}
	} else {
		switch (size) {
			case 24:
				return avatar_24x24
			case 32:
				return avatar_32x32
			case 64:
				return avatar_64x64
			case 128:
				return avatar_128x128
			default:
				return avatar_32x32
		}
	}
}
const KImg: FC<KImagProps> = ({ src, size = 32, accountType }) => {
	const [imgSrc, setImgSrc] = useState<string>(() => src)
	const onError = () => {
		if (imgSrc === getDefaultAvatarUrl(accountType, size)) return
		setImgSrc(getDefaultAvatarUrl(accountType, size))
	}
	return <img src={imgSrc} alt="" onError={onError} />
}
export function Avatar<T extends Ix>({ value }: AvatarProps<T>) {
	const useAvatar = useGlobalStore((state) => state.user?.personal_config?.mt_portrait_type === 1)
	if (value.isMt) {
		const {
			portrait,
			accountType,
			isPhone,
			isSimpleCascade,
			status: { isOnline, isManager },
		} = value
		return (
			<Wrap
				useAvatar={useAvatar}
				hasAvatar={!!portrait}
				isOnline={isOnline}
				isManager={isManager}
				isPhone={isPhone}
				isMeeting={isSimpleCascade}
			>
				{useAvatar && !!portrait && <KImg src={portrait} accountType={accountType} />}
			</Wrap>
		)
	} else {
		const {
			status: { isOnline, isManager },
		} = value
		return (
			<Wrap
				useAvatar={useAvatar}
				hasAvatar={false}
				isOnline={isOnline}
				isManager={isManager}
				isPhone={false}
				isMeeting={true}
			/>
		)
	}
}
